package com.eduction.controller;

import com.eduction.bean.ExpertAndIdentity;
import com.eduction.bean.ItemListExpertBean;
import com.eduction.bean.SessionUser;
import com.eduction.bean.SurveyProblemBean;
import com.eduction.common.DocumentHandler;
import com.eduction.common.ReturnCode;
import com.eduction.modules.system.entity.*;
import com.eduction.modules.target.entity.Detailed;
import com.eduction.modules.target.entity.IndexTargetEntity;
import com.eduction.modules.target.entity.ObservationPoint;
import com.eduction.modules.target.entity.SonTarget;
import com.eduction.resource.BaseController;
import com.eduction.service.*;
import com.eduction.vo.ExpectGroupSchoolVo;
import com.eduction.vo.ExpertGroupVo;
import com.eduction.vo.SurveyOpinionVo;
import org.apache.bcel.generic.NEW;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/allocation")
@Transactional
public class ExpertAllocationController extends BaseController {

    private static final Logger log = Logger.getLogger(ExpertAllocationController.class);
    @Value("${doc.path}")
    private String docPath;
    @Autowired
    private ExpertGroupMapService expertGroupMapService;
    @Autowired
    private ExpertItemMapService expertItemMapService;
    @Autowired
    private SiteInspectionExpertService siteInspectionExpertService;
    @Autowired
    private IndexTargetEntityService indexTargetEntityService;
    @Autowired
    private SurveyOpinionService surveyOpinionService;
    @Autowired
    private SonTargetService sonTargetService;
    @Autowired
    private DetailedService detailedService;
    @Autowired
    private SurveyProblemService surveyProblemService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private ObservationPointService observationPointService;
    @Autowired
    private  ObservationService observationService;

    /**
     * 专家组长分工
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/saveExpertItemMap", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> saveExpertItemMap(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String itemList=map.get("itemList");
        String expertId = map.get("expertId");
        String schoolId = map.get("schoolId");
        if (StringUtils.isBlank(itemList) || StringUtils.isBlank(schoolId)) {
            return toResponse(null, ReturnCode.FAIL, "参数存在空值");
        }
        if(expertId==null) {
            expertId= (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        }
        if (null == expertId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        String[] items=itemList.split("#");
        String[] schoolIds=schoolId.split("#");

        String type= (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        try {
            ExpertGroupMap eg = expertGroupMapService.queryGroupByExpertId(expertId,type);
            if (null == eg) {
                return toResponse(null, ReturnCode.FAIL, "未分配组或考察结束");
            }
            for(int i=0;i<schoolIds.length;i++) {
                expertItemMapService.deleteBySchoolIdAndExpertId(schoolIds[i],expertId, type);
            }
            for(int i=0;i<items.length;i++){
                String[] itemId = items[i].split(",");
                if (itemId.length > 0) {
                    for (int j = 0; j < itemId.length; j++) {
                        ExpertItemMap ei = new ExpertItemMap();
                        ei.setS_expert_id(expertId);
                        ei.setS_school_id(schoolIds[i]);
                        ei.setS_item_id(itemId[j]);
                        ei.setS_type(type);
                        expertItemMapService.saveExpertItemMap(ei);
                    }
                }
            }
            return toResponse(null, ReturnCode.SUCCESS, "分配任务成功!");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "分配任务失败!");
        }
    }

    /**
     * 专家查询已分配专家情况
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryExpectItem", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> queryExpectItem(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String expertId = map.get("expertId");
        if(expertId==null) {
            expertId= (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        }
        if (null == expertId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        String type= (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
//        String type="1";
        try {
            ExpertGroupMap eg = expertGroupMapService.queryGroupByExpertId(expertId,type);
            if (null == eg) {
                return toResponse(null, ReturnCode.FAIL, "未分配组或考察结束");
            }
            String groupId=eg.getS_group_id();
            List<ExpertGroupMap> egList=expertGroupMapService.querySchoolByGroupId(groupId);

            List<ExpertGroupVo> expertGroupVoList=new ArrayList<>();
            for(ExpertGroupMap egMap:egList){
                ExpertGroupVo expertGroupVo=new ExpertGroupVo();
                BeanUtils.copyProperties(egMap,expertGroupVo);
                List<ItemListExpertBean> itemListExpertBeanList=expertItemMapService.queryListByExpertId(expertId,type,null);
                //设置专家姓名
                Expert expert=observationService.queryExpertInfo(egMap.getS_expert_id());
                expertGroupVo.setS_expect_name(expert.getS_name());
                //获取所有组内学校ID
                List<ItemListExpertBean> itemListExpertBeanList2=expertItemMapService.groupBySchoolId(expertId,type);
                List<ExpectGroupSchoolVo> expectGroupSchoolVoList=new ArrayList<>();
                for(ItemListExpertBean itemListExpertBean2:itemListExpertBeanList2 ){
                    ExpectGroupSchoolVo expectGroupSchoolVo=new ExpectGroupSchoolVo();
                    expectGroupSchoolVo.setSchoolId(itemListExpertBean2.getSchoolId());

                    List<ItemListExpertBean> itemListExpertBeanList3=new ArrayList<>();
                    for(ItemListExpertBean itemListExpertBean: itemListExpertBeanList){
                        if(itemListExpertBean2.getSchoolId()!=null&&itemListExpertBean2.getSchoolId().equals(itemListExpertBean.getSchoolId())){
                            expectGroupSchoolVo.setSchoolName(itemListExpertBean.getSchoolName());
                            itemListExpertBeanList3.add(itemListExpertBean);
                        }
                    }
                    expectGroupSchoolVo.setList(itemListExpertBeanList3);
                    expectGroupSchoolVoList.add(expectGroupSchoolVo) ;
                }
                expertGroupVo.setList(expectGroupSchoolVoList);
                expertGroupVoList.add(expertGroupVo);
            }
            return toResponse(expertGroupVoList, ReturnCode.SUCCESS, "查询该组专家分配任务成功!");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询该组专家分配任务失败!");
        }
    }


    /**
     * 查询与专家组绑定的学校
     */
    @RequestMapping(value = "/querySchoolGroupMap", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> querySchoolGroupMap(HttpServletRequest request) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        try {
            ExpertGroupMap eg = expertGroupMapService.queryGroupByExpertId(pId,type);

            if (null == eg) {
                return toResponse(null, ReturnCode.FAIL, "未分配组或考察结束");
            }
            List<School> list = siteInspectionExpertService.querySchoolByGroup(eg.getS_group_id());
            if (list == null) {
                return toResponse(null, ReturnCode.FAIL, "请先添加学校");
            }
            return toResponse(list, ReturnCode.SUCCESS, "学校列表查询成功!");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "学校列表查询失败!");
        }
    }


    /**
     * 查询分配指标
     */
    @RequestMapping(value = "/queryExpertItemMap", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> queryExpertItemMap(HttpServletRequest request, @RequestBody Map<String, String> map) {

        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }
        String schoolId = map.get("schoolId");
        String type= (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if (StringUtils.isBlank(schoolId)) {
            return toResponse(null, ReturnCode.FAIL, "请选择学校!");
        }
        try {
            List<IndexTargetEntity> list = indexTargetEntityService.queryAllIndexTarget();
            if (list == null)
                return toResponse(null, ReturnCode.FAIL, "暂无数据");
            List<ExpertItemMap> lt = expertItemMapService.queryInfoBySchoolId(schoolId,type);
            List<IndexTargetEntity> l = new ArrayList<>();
            if (null != lt) {
                for (IndexTargetEntity it : list) {
                    it.setFlag("0");
                    for (int j = 0; j < lt.size(); j++) {
                        if (it.getP_id().equals(lt.get(j).getS_item_id())) {
                            it.setFlag("1");
                        }
                    }
                    l.add(it);
                }
            }
            return toResponse(l, ReturnCode.SUCCESS, "查询成功!");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询失败!");
        }
    }

    /**
     * 查询专家组成员
     */
    @RequestMapping(value = "/queryExpertGroupInfo", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> queryExpertGroupInfo(HttpServletRequest request) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String type=(String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        try {
            ExpertGroupMap eg = expertGroupMapService.queryGroupByExpertId(pId,type);
            if (null == eg) {
                return toResponse(null, ReturnCode.FAIL, "未分配组或考察结束");
            }
            String groupId = eg.getS_group_id();
            List<ExpertAndIdentity> list = siteInspectionExpertService.selectExpertByGroup(groupId);
            return toResponse(list, ReturnCode.SUCCESS, "查询成功!");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询失败!");
        }
    }

    /**
     * 查询一级指标专项考察列表
     */
    @RequestMapping(value = "/queryItemListByExpert", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> queryItemListByExpert(HttpServletRequest request) throws SQLException {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        String schoolId =request.getParameter("schoolId");
        String schoolName =request.getParameter("schoolName");
        String identity = (String) request.getSession().getAttribute(SessionUser.IDENTITY);
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }else {
            try {
                List<ItemListExpertBean> list = new ArrayList<>();
//                if ("4".equals(type)) {
                if (StringUtils.isNotBlank(schoolId)&&StringUtils.isNotBlank(schoolName)) {
                    List<IndexTargetEntity> list1 = indexTargetEntityService.queryAllIndexTarget();
                    for (IndexTargetEntity entity : list1) {
                        ItemListExpertBean bean = new ItemListExpertBean();
                        bean.setItemId(entity.getP_id());
                        bean.setItemName(entity.getS_name());
                        bean.setSchoolId(schoolId);
                        bean.setSchoolName(schoolName);
                        bean.setType(String.valueOf(entity.getS_type()));
                        list.add(bean);
                    }
                } else {
                    list = expertItemMapService.queryListByExpertId(pId, type, identity);
                    if (null == list) {
                        return toResponse(null, ReturnCode.SUCCESS, "请组长分配任务!");
                    }

                }
                return toResponse(list, ReturnCode.SUCCESS, "查询成功!");
            } catch (SQLException e) {
                log.error(e);
                return toResponse(null, ReturnCode.FAIL, "查询失败!");
            }
        }

    }

    /**
     * 查询一级指标考察意见数据
     */
    @RequestMapping(value = "/querySurveyOpinionData", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> querySurveyOpinionData(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String identify=(String) request.getSession().getAttribute(SessionUser.IDENTITY);
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        String type = map.get("type");
        if(type==null||"".equals(type)) {
            type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        }
        String expectType = null;
        if ("1".equals(type)) {
            expectType = "0";
        } else {
            expectType = "1";
        }
        String schoolId = map.get("schoolId");
        School s= null;
        try {
            s = schoolService.queryById(schoolId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String itemId = map.get("itemId");
        if (StringUtils.isBlank(itemId) || StringUtils.isBlank(schoolId)) {
            return toResponse(null, ReturnCode.FAIL, "参数不能为空");
        }
        try {
            List<SurveyOpinion> ls = new ArrayList<>();
            List<SonTarget> list = sonTargetService.querySonTargetByFid(itemId);
            if (list == null)
                return toResponse(null, ReturnCode.FAIL, "二级指标不存在!");

            for (int i = 0; i < list.size(); i++) {
                List<Detailed> list1 = detailedService.queryDetailedByFid(list.get(i).getP_id(),s.getP_type_id());
                for (int j = 0; j < list1.size(); j++) {
                    SurveyOpinion lt = new SurveyOpinion();
                    if("10000".equals(pId)||"3".equals(identify)){
                        lt = surveyOpinionService.querySurveyOpinionInfo(list1.get(j).getP_id(), schoolId, expectType);

                    }else {
                        lt = surveyOpinionService.querySurveyOpinionInfo(pId, list1.get(j).getP_id(), schoolId,expectType);
                    }
                    ls.add(lt);
                }
            }

            return toResponse(ls, ReturnCode.SUCCESS, "查询专家某一学校一级指标分项考察意见表数据成功");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询专家某一学校一级指标分项考察意见表数据失败!");
        }
    }

    /**
     * 查询问题
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/querySurveyProblemData", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> querySurveyProblemData(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String identify= (String) request.getSession().getAttribute(SessionUser.IDENTITY);
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        String type = map.get("type");
        if("".equals(type)||type==null) {
            type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        }
        String expectType = null;
        if ("1".equals(type)) {
            expectType = "0";
        } else {
            expectType = "1";
        }
        String schoolId = map.get("schoolId");
        String itemId = map.get("itemId");
        if (StringUtils.isBlank(itemId) || StringUtils.isBlank(schoolId)) {
            return toResponse(null, ReturnCode.FAIL, "参数不能为空");
        }
        try {
            SurveyProblem s=null;


           if("10000".equals(pId)||"3".equals(identify)){
               List<SurveyProblem> list = surveyProblemService.querySurveyProblemData(itemId, schoolId, expectType);
               if(list!=null&&list.size()>0)
                   s=list.get(0);
           }else{
                s = surveyProblemService.querySurveyProblemData(pId, itemId, schoolId, expectType);
            }
            SurveyProblemBean surveyProblemBean=null;
            if(s!=null) {
                surveyProblemBean = new SurveyProblemBean();
                BeanUtils.copyProperties(s, surveyProblemBean);
                Expert et=observationService.queryExpertInfo(s.getS_expert_id());
                if(et!=null)
                surveyProblemBean.setS_expert_name(et.getS_name());
            }

            return toResponse(surveyProblemBean, ReturnCode.SUCCESS, "查询专家某一学校一级指标分项考察意见表数据成功");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询专家某一学校一级指标分项考察意见表数据失败!");
        }
    }

    /**
     * 保存一级指标考察意见数据
     */
    @RequestMapping(value = "/saveSurveyOpinionData", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> saveSurveyOpinionData(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        String expectType = null;
        if ("1".equals(type)) {
            expectType = "0";//材料评审
        } else {
            expectType = "1";//现场考察
        }
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        String schoolId = map.get("schoolId");
        String itemId = map.get("itemId");//三级指标id
        String keys = map.get("keys");
        String values = map.get("values");
        String modes = map.get("modes");

        String itemId1 = map.get("itemId1");//一级指标id
        String analysis = map.get("analysis");//分析
        String problem = map.get("problem");//问题
        String suggest = map.get("suggest");//建议
        if (StringUtils.isBlank(itemId) || StringUtils.isBlank(schoolId) || StringUtils.isBlank(keys) || StringUtils.isBlank(values) || StringUtils.isBlank(modes)) {
            return toResponse(null, ReturnCode.FAIL, "参数不能为空");
        }
        if (StringUtils.isBlank(itemId1) || StringUtils.isBlank(analysis) || StringUtils.isBlank(problem) || StringUtils.isBlank(suggest)) {
            return toResponse(null, ReturnCode.FAIL, "参数不能为空");
        }
        String[] itemIdList = itemId.split("#");
        String[] keyList = keys.split("#");
        String[] valueList = values.split("#");
        String[] modeList = modes.split("#");
        if ("1".equals(type)) {
            for (int i = 0; i < itemIdList.length; i++) {
                try {
                    surveyOpinionService.deleteAuthIinspectionOpinionss(schoolId, itemIdList[i], pId, 0);
                } catch (SQLException e) {
                    log.error(e);
                    return toResponse(null, ReturnCode.FAIL, "保存专家某一学校一级指标分项考察意见表数据失败!");
                }
            }
        } else if ("2".equals(type)) {
            for (int i = 0; i < itemIdList.length; i++) {
                try {
                    surveyOpinionService.deleteAuthIinspectionOpinionss(schoolId, itemIdList[i], pId, 1);
                } catch (SQLException e) {
                    log.error(e);
                    return toResponse(null, ReturnCode.FAIL, "保存专家某一学校一级指标分项考察意见表数据失败!");
                }
            }
        }
        try {
            List<SurveyOpinion> list = new ArrayList<>();
            if (keyList.length > 0) {
                String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                for (int i = 0; i < keyList.length; i++) {
                    SurveyOpinion s = new SurveyOpinion();
                    s.setS_expert_id(pId);
                    s.setS_item_id(itemIdList[i]);
                    s.setS_school_id(schoolId);
                    s.setS_key(keyList[i]);
                    s.setS_value(valueList[i]);
                    s.setS_mode(modeList[i]);
                    s.setS_create_time(nowTime);
                    s.setS_type(expectType);
                    list.add(s);
                }
            }

            String nowTime1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            surveyProblemService.deleteSurveyProblem(pId, schoolId, itemId1, expectType);
            SurveyProblem s = new SurveyProblem();
            s.setS_expert_id(pId);
            s.setS_item_id(itemId1);
            s.setS_school_id(schoolId);
            s.setS_analysis(analysis);
            s.setS_problem(problem);
            s.setS_suggest(suggest);
            s.setS_create_time(nowTime1);
            s.setS_type(expectType);
            surveyProblemService.saveSurveyProblem(s);
            surveyOpinionService.saveSurveyOpinionInfo(list);
            return toResponse(null, ReturnCode.SUCCESS, "保存专家某一学校一级指标分项考察意见表数据成功");
        } catch (Exception e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "保存专家某一学校一级指标分项考察意见表数据失败!");
        }
    }

    /**
     * 组长汇总表
     */
    @RequestMapping(value = "/queryPool", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> queryPool(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        String expectType = null;
        if ("1".equals(type)) {
            expectType = "0";
        } else {
            expectType = "1";
        }
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        String schoolId = map.get("schoolId");
        School s= null;
        String schoolType="0";
        try {
            s = schoolService.queryById(schoolId);
            if("1495071155575000".equals(s.getP_type_id())){
                schoolType="0";
            }else{
                schoolType="1";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(schoolId)) {
            return toResponse(null, ReturnCode.FAIL, "参数不能为空");
        }
        try {
            List<SurveyOpinion> ls = new ArrayList<>();
            List<SurveyOpinionVo> voList = new ArrayList<>();
            //List<SurveyOpinion> list = surveyOpinionService.queryAllSurveyOpinion(schoolId,mode);
            List<IndexTargetEntity> list1 = indexTargetEntityService.queryAllIndexTarget();
            if (list1 == null)
                return toResponse(null, ReturnCode.FAIL, "暂无数据");
            for (int i = 0; i < list1.size(); i++) {
                List<SonTarget> list2 = sonTargetService.querySonTargetByFid(list1.get(i).getP_id());
                if (list2 == null) {
                    return toResponse(null, ReturnCode.FAIL, "二级指标不存在!");
                }
                for (int j = 0; j < list2.size(); j++) {
                    List<Detailed> list3 = detailedService.queryDetailedByFid(list2.get(j).getP_id(),schoolType);
                    if (list3 == null) {
                        return toResponse(null, ReturnCode.FAIL, "细则不存在!");
                    }
                    for (int k = 0; k < list3.size(); k++) {
                        SurveyOpinion lt = surveyOpinionService.querySurveyOpinionInfo(pId, list3.get(k).getP_id(), schoolId,expectType);
                        SurveyOpinionVo vo = new SurveyOpinionVo();
                        if (lt != null) {
                            BeanUtils.copyProperties(lt, vo);
                        }
                        vo.setTitle((i + 1) + "." + (j + 1) + "." + (k + 1));
                        //ls.add(lt);
                        voList.add(vo);
                    }
                }
            }

            return toResponse(voList, ReturnCode.SUCCESS, "查询专家某一学校一级指标分项考察意见表数据成功");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询专家某一学校一级指标分项考察意见表数据失败!");
        }

    }

    /**
     * 一级指标三级查询
     */
    @RequestMapping(value = "/queryDetailedData", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> queryDetailedData(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String schoolType = (String) request.getSession().getAttribute(SessionUser.SCHOOL_TYPE);

        String type=map.get("type");
        if(type==null||"".equals(type)) {
            type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        }
        String expectType = null;
        if ("1".equals(type)) {
            expectType = "0";
        } else {
            expectType = "1";
        }
        String itemId= map.get("itemId");
        String schoolId=map.get("schoolId");
        try {
            if(schoolId!=null) {
                School school = schoolService.querySchoolByAccount(schoolId);
                if ("1495071155575000".equals(school.getP_type_id())) {
                    schoolType="0";
                } else {
                    schoolType="1";
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(itemId)) {
            return toResponse(null, ReturnCode.FAIL, "参数不能为空");
        }
        try {
            List<SonTarget> list = sonTargetService.querySonTargetByFid(itemId);
            if (list == null)
                return toResponse(null, ReturnCode.FAIL, "二级指标不存在!");
            List<SonTarget> lt = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                List<Detailed> list1 = detailedService.queryDetailedByFid(list.get(i).getP_id(),schoolType);
               int j=1;
                for(Detailed d:list1){
                    String obGrade="";
                    List<SurveyOpinion> opList= surveyOpinionService.queryItemSurveyOpinion(schoolId,d.getP_id(),expectType);
                    for(SurveyOpinion op:opList){
                        if("".equals(obGrade)) {
                            obGrade = op.getS_key();
//                        }else{
////                            obGrade=obGrade+"#"+op.getS_key();
////                        }
                        }
                    }
//                    d.setOpList(opList);
                    d.setGrade(obGrade);
                    d.setS_number(String.valueOf(j));
                    j++;
                }

                SonTarget son = new SonTarget();
                son.setP_id(list.get(i).getP_id());
                son.setP_index_id(list.get(i).getP_index_id());
                son.setS_create_time(list.get(i).getS_create_time());
                son.setS_name(list.get(i).getS_name());
                son.setS_status(list.get(i).getS_status());
                son.setS_type(list.get(i).getS_type());
                son.setS_number(list.get(i).getS_number());
                son.setList(list1);
                lt.add(son);
            }
            return toResponse(lt, ReturnCode.SUCCESS, "查询成功!");
        } catch (SQLException e) {
            log.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询失败!");
        }
    }

    /**
     * 下载专家分工指标考察意见
     */
    @RequestMapping(value = "/writeWordFile", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public void exportSurveyOpinionData(HttpServletRequest request, HttpServletResponse response, String
            schoolId, String itemId) {
        Map<String, Object> dataMap = new HashMap<String, Object>();

        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return ;
        }
        String expertId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        if (null == expertId) {
            log.error("未登录");
        }
        String eType = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        String expectType = null;
        if ("1".equals(eType)) {
            expectType = "0";
        } else {
            expectType = "1";
        }
        try {
            School s = schoolService.querySchoolById(schoolId);
            String type = s.getTypeName();
            dataMap.put("type", type);
            String school = s.getS_name();
            dataMap.put("school", school);

            IndexTargetEntity it = indexTargetEntityService.queryIndexTargetById(itemId);
            dataMap.put("item", it.getS_name());

            List<SonTarget> list2 = sonTargetService.querySonTargetByFid(itemId);//二级指标

            List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();

            for (int i = 0; i < list2.size(); i++) {

                int gradeA = 0;
                int gradeB = 0;
                int gradeC = 0;
                Map<String, Object> map = new HashMap<String, Object>();
                List<Detailed> list1 = detailedService.queryDetailedByFid(list2.get(i).getP_id(),s.getP_type_id());//细则
                map.put("two", list2.get(i).getS_number() + list2.get(i).getS_name());
                l.add(map);
                for (int j = 0; j < list1.size(); j++) {
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    map1.put("number", list1.get(j).getS_number());
                    SurveyOpinion lt = surveyOpinionService.querySurveyOpinionInfo(expertId, list1.get(j).getP_id(), schoolId,expectType);
                    if (lt != null) {
                        if ("A".equals(lt.getS_key())) {
                            gradeA++;
                        } else if ("B".equals(lt.getS_key())) {
                            gradeB++;
                        } else if ("C".equals(lt.getS_key())) {
                            gradeC++;
                        }
                        map1.put("level", lt.getS_key());
                        map1.put("value", lt.getS_value());
                    } else {
                        map1.put("level", "未评价");
                        map1.put("value", "");
                    }
                    l.add(map1);
                }
                if (gradeC > 0) {
                    map.put("grade", "C");
                } else if (gradeB > 0 && gradeC == 0) {
                    map.put("grade", "B");
                } else if (gradeB == 0 && gradeC == 0 && gradeA > 0) {
                    map.put("grade", "A");
                } else if (gradeB == 0 && gradeC == 0 && gradeA == 0) {
                    map.put("grade", "未评价");
                }
            }
            dataMap.put("list", l);

            SurveyProblem sp = surveyProblemService.querySurveyProblemData(expertId, itemId, schoolId,expectType);
            if (sp != null) {
                dataMap.put("problem1", sp.getS_analysis());
                dataMap.put("problem2", sp.getS_problem());
                dataMap.put("problem3", sp.getS_suggest());
            } else {
                dataMap.put("problem1", "");
                dataMap.put("problem2", "");
                dataMap.put("problem3", "");
            }
            DocumentHandler mdoc = new DocumentHandler();
            mdoc.createDoc1(request, response, dataMap, docPath + school + it.getS_name() + ".doc");
        } catch (UnsupportedEncodingException e) {
            log.error(e);
        } catch (SQLException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }
    }


}
